package com.ubb.damate.service.impl;

import java.util.List;

import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import javax.persistence.TypedQuery;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import com.ubb.damate.model.Workspace;
import com.ubb.damate.service.WorkspaceServiceLocal;
import com.ubb.damate.service.WorkspaceServiceRemote;

/** Session Bean implementation class WorkspaceService */
@Stateless
public class WorkspaceService implements WorkspaceServiceRemote, WorkspaceServiceLocal {

	@PersistenceContext(unitName = "damate-pu")
	private EntityManager	em;

	@Override
	public Workspace createOrUpdate(Workspace workspace) {
		return em.merge(workspace);
	}

	@Override
	public void delete(Workspace workspace) {
		em.remove(em.merge(workspace));
	}

	@Override
	public Workspace find(Workspace workspace) {
		return em.find(com.ubb.damate.model.Workspace.class, workspace);
	}

	@Override
	public Workspace find(String username, String path) {
		CriteriaBuilder criteriaBuilder = em.getCriteriaBuilder();
		CriteriaQuery<Workspace> criteriaQuery = criteriaBuilder.createQuery(Workspace.class);
		Root<Workspace> from = criteriaQuery.from(Workspace.class);
		Predicate condition = criteriaBuilder.equal(from.get("username"), username);
		Predicate condition2 = criteriaBuilder.equal(from.get("path"), path);
		Predicate condition3 = criteriaBuilder.and(condition, condition2);
		criteriaQuery.where(condition3);
		Query query = em.createQuery(criteriaQuery);

		return (Workspace) query.getSingleResult();
	}

	@Override
	@SuppressWarnings("unchecked")
	public List<Workspace> find(String username) {
		/*CriteriaBuilder criteriaBuilder = em.getCriteriaBuilder();
		CriteriaQuery<Workspace> criteriaQuery = criteriaBuilder.createQuery(Workspace.class);
		Root<Workspace> from = criteriaQuery.from(Workspace.class);
		Predicate condition = criteriaBuilder.equal(from.get("username"), username);
		criteriaQuery.where(condition);
		Query query = em.createQuery(criteriaQuery);

		return (List<Workspace>) query.getResultList();*/

		String queryStr = "SELECT NEW com.ubb.damate.model.Workspace(w.creationDate, w.username, w.path) " + "FROM Workspace AS w WHERE w.username = ?1";
		TypedQuery<Workspace> query = em.createQuery(queryStr, Workspace.class);
		query.setParameter(1, username);
		List<Workspace> results = query.getResultList();

		return results;
	}
}